# -*- coding: utf-8 -*-

import os
import datetime
from datetime import datetime as _date


class MySqlBackupTools(object):
    def __init__(self, db_backup_dir=r"C:/Users/Administrator/Desktop/package"):
        self.db_backup_dir = db_backup_dir

    def backup_db(self, db_host="127.0.0.1", db_port="3306", db_user="root", db_pw="root",
        db_name="dwc-admin", db_charset="utf8"):
        print("Begin to dump mysql database： '%s'..." % db_name)
        os.system("mysqldump -h%s -P%s -u%s -p%s %s --master-data=2 -F --default_character-set=%s | gzip > %s" % (
            db_host, db_port, db_user, db_pw, db_name, db_charset,
            os.path.join(self.db_backup_dir,db_name+"."+_date.now().strftime("%Y_%m_%d-%H:%M:%S")+".sql.gz")))
        print("Dump database: '%s' is complete." % db_name);
        #os.system("ls -hlt " + self.db_backup_dir + " | head -3")

    def check_file_timeout(self, specified_date=_date.now(), out_times=60*(24*60*60), check_name=True):
        file_names = os.listdir(self.db_backup_dir)
        for fn in file_names:
            if check_name:
                try:
                    # print "---------" + fn + "---" + fn[4:23]
                    file_date = _date.strptime(fn[4:23], "%Y_%m_%d-%H:%M:%S")
                except ValueError:
                    print("check_name failed...., @ %s ." % fn)
                    continue
                    # file_date = _date.fromtimestamp(os.path.getmtime(fn))
            else:
                file_date = _date.fromtimestamp(os.path.getmtime(fn))

            if specified_date - datetime.timedelta(seconds=out_times) > file_date:
                os.remove(os.path.join(self.db_backup_dir,fn))
                print("Remove file (" + fn + ")")
            else:
                print("Keep file (" + fn + ")");

if __name__ == "__main__":
    myTool = MySqlBackupTools()
    myTool.backup_db()
    #myTool.check_file_timeout()
